package jjn.round2;

/**
 * @author Jiang Jining
 * @since 2023-05-03 12:56
 */
public class Offer53_FindTargetInArray {
    public int search(int[] nums, int target) {
        int left = 0, right = nums.length - 1;
        while (left <= right) {
            int mid = (right - left) / 2 + left;
            if (nums[mid] == target) {
                int maxLeft = mid, maxRight = mid;
                while (maxRight < nums.length && nums[maxRight] == target) {
                    maxRight++;
                }
                while (maxLeft >= 0 && nums[maxLeft] == target) {
                    maxLeft--;
                }
                return maxRight - maxLeft - 1;
            }
            if (nums[mid] < target) {
                left = mid + 1;
                continue;
            }
            if (nums[mid] > target) {
                right = mid - 1;
            }
        }
        return 0;
    }
}
